package com.mimosa.util.config.ini;

class OptionFormat {

	private static final int EXPECTED_TOKENS = 4;

	private String[] formatTokens;

	public OptionFormat(String formatString) {
		this.formatTokens = this.compileFormat(formatString);
	}

	public String format(String name, String value, char separator) {
		String[] t = this.formatTokens;
		return t[0] + name + t[1] + separator + t[2] + value + t[3];
	}

	private String[] compileFormat(String formatString) {
		String[] tokens = { "", "", "", "" };
		int tokenCount = 0;
		boolean seenPercent = false;
		StringBuffer token = new StringBuffer();
		for (int i = 0; i < formatString.length(); i++) {
			switch (formatString.charAt(i)) {
			case '%':
				if (seenPercent) {
					token.append("%");
					seenPercent = false;
				} else {
					seenPercent = true;
				}
				break;
			case 's':
				if (seenPercent) {
					if (tokenCount >= EXPECTED_TOKENS) {
						throw new IllegalArgumentException("Illegal option format. Too many %s placeholders.");
					}
					tokens[tokenCount] = token.toString();
					tokenCount++;
					token = new StringBuffer();
					seenPercent = false;
				} else {
					token.append("s");
				}
				break;
			default:
				if (seenPercent) {
					throw new IllegalArgumentException("Illegal option format. Unknown format specifier.");
				}
				token.append(formatString.charAt(i));
				break;
			}
		}
		if (tokenCount != EXPECTED_TOKENS - 1) {
			throw new IllegalArgumentException("Illegal option format. Not enough %s placeholders.");
		}
		tokens[tokenCount] = token.toString();
		return tokens;
	}
}
